<template>
  <div
    :style="{ height: props.height, width: props.width }"
    ref="chartsRef"
    :id="id"
  ></div>
</template>

<script name="LrCharts" setup>
// import { idGen } from "@/utils/index.js";
import * as echarts from "echarts";
import "echarts-liquidfill";
import {
  ref,
  onMounted,
  onBeforeUnmount,
  useAttrs,
  useSlots,
  computed,
  watch,
  shallowRef,
  defineProps,
  defineEmits,
  defineExpose
} from "vue";

defineOptions({
  inheritAttrs: false,
});

const props = defineProps({
  height: {
    des: "高度，默认100%适应容器",
    type: String,
    default: "100%",
  },
  width: {
    des: "宽度，默认100%适应容器",
    type: String,
    default: "100%",
  },
  options: {
    des: "配置项",
    type: Object,
    default: {},
  },
});

const slots = useSlots(); 
const attrs = useAttrs(); 
const charts = shallowRef(null); 
const id = ref(""); 
const chartsRef = ref(); 

watch(
  () => props.options,
  (val) => {
    if (charts.value) {
      initCharts();
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

watch(
  () => [props.width, props.height], 
  () => {
    if (charts.value) {
      resizeCharts();
    }
  }
);

onMounted(() => {
  id.value = "lr-chart-" + idGen();
  initCharts();
  window.addEventListener("resize", resizeCharts);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeCharts);
  if (charts.value) {
    charts.value.dispose(); 
    charts.value = null;
  }
});

const emit = defineEmits(["click"]);

function initCharts() {
  if (charts.value) {
    charts.value.setOption(props.options, true);
  } else {
    charts.value = echarts.init(chartsRef.value);
    charts.value.setOption(props.options, true);
    charts.value.on("click", function (params) {
      emit("click", params);
    });
  }
}

function resizeCharts() {
  charts.value.resize({
    animation: 300,
  });
}
function idGen(){
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x'? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

defineExpose({
  initCharts,
  resizeCharts,
  getChartInstance: () => charts.value, 
});
</script>

<style lang="less" scoped>
</style>